<template>
  <div class="materials">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="物料编码">
          <el-input v-model="searchForm.code" placeholder="请输入物料编码" clearable />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.name" placeholder="请输入物料名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="原材料" value="raw" />
            <el-option label="半成品" value="semi" />
            <el-option label="成品" value="finished" />
            <el-option label="包装物" value="package" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="handleAdd" v-if="hasPermission('purchase:material:add')">
        <el-icon><Plus /></el-icon>新增物料
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="code" label="物料编码" width="120" />
        <el-table-column prop="name" label="物料名称" width="200" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">
              {{ getCategoryText(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号" width="150" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="price" label="标准价格" width="120">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit(row)"
              v-if="hasPermission('purchase:material:edit')"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              v-if="hasPermission('purchase:material:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="原材料" value="raw" />
                <el-option label="半成品" value="semi" />
                <el-option label="成品" value="finished" />
                <el-option label="包装物" value="package" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位" style="width: 100%">
                <el-option label="个" value="个" />
                <el-option label="件" value="件" />
                <el-option label="套" value="套" />
                <el-option label="箱" value="箱" />
                <el-option label="kg" value="kg" />
                <el-option label="m" value="m" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格型号" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标准价格" prop="price">
              <el-input-number v-model="form.price" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="active">正常</el-radio>
                <el-radio value="inactive">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入物料描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 搜索表单
const searchForm = reactive({
  code: '',
  name: '',
  category: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  code: '',
  name: '',
  category: '',
  specification: '',
  unit: '',
  price: 0,
  status: 'active',
  description: ''
})

// 表单验证规则
const formRules = {
  code: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
  price: [{ required: true, message: '请输入标准价格', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    code: 'M001',
    name: '原材料A',
    category: 'raw',
    specification: '规格A',
    unit: 'kg',
    price: 10.50,
    stock: 1000,
    status: 'active',
    description: '主要原材料',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    code: 'M002',
    name: '半成品B',
    category: 'semi',
    specification: '规格B',
    unit: '件',
    price: 25.00,
    stock: 500,
    status: 'active',
    description: '加工半成品',
    createTime: '2024-01-14 14:20:00'
  },
  {
    id: 3,
    code: 'M003',
    name: '成品C',
    category: 'finished',
    specification: '规格C',
    unit: '套',
    price: 150.00,
    stock: 200,
    status: 'active',
    description: '最终产品',
    createTime: '2024-01-13 09:15:00'
  },
  {
    id: 4,
    code: 'M004',
    name: '包装盒',
    category: 'package',
    specification: '标准包装',
    unit: '个',
    price: 2.50,
    stock: 2000,
    status: 'inactive',
    description: '产品包装',
    createTime: '2024-01-12 16:45:00'
  },
  {
    id: 5,
    code: 'M005',
    name: '电子元件',
    category: 'raw',
    specification: 'IC芯片',
    unit: '片',
    price: 15.80,
    stock: 800,
    status: 'active',
    description: '集成电路芯片',
    createTime: '2024-01-11 11:20:00'
  },
  {
    id: 6,
    code: 'M006',
    name: '机械零件',
    category: 'semi',
    specification: '轴承',
    unit: '个',
    price: 8.50,
    stock: 1200,
    status: 'active',
    description: '精密轴承',
    createTime: '2024-01-10 09:30:00'
  },
  {
    id: 7,
    code: 'M007',
    name: '化工原料',
    category: 'raw',
    specification: '树脂',
    unit: 'kg',
    price: 12.00,
    stock: 1500,
    status: 'active',
    description: '工业用树脂',
    createTime: '2024-01-09 14:15:00'
  },
  {
    id: 8,
    code: 'M008',
    name: '软件授权',
    category: 'finished',
    specification: '企业版',
    unit: '套',
    price: 5000.00,
    stock: 50,
    status: 'active',
    description: '企业级软件授权',
    createTime: '2024-01-08 10:45:00'
  }
]

// 获取分类类型
const getCategoryType = (category) => {
  const typeMap = {
    raw: 'primary',
    semi: 'warning',
    finished: 'success',
    package: 'info'
  }
  return typeMap[category] || 'info'
}

// 获取分类文本
const getCategoryText = (category) => {
  const textMap = {
    raw: '原材料',
    semi: '半成品',
    finished: '成品',
    package: '包装物'
  }
  return textMap[category] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    code: '',
    name: '',
    category: '',
    status: ''
  })
  handleSearch()
}

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增物料'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑物料'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看功能开发中...')
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个物料吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟删除
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交
    setTimeout(() => {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    category: '',
    specification: '',
    unit: '',
    price: 0,
    status: 'active',
    description: ''
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.materials {
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 